import ccxt.async_support as ccxt
import asyncio

async def fetch_data(exchange, symbol):
    # 获取市场数据
    ticker = await exchange.fetch_ticker(symbol)
    return ticker

async def fetch_loop():
    # 初始化交易所实例
    binance = ccxt.binance()
    bitget = ccxt.bitget()

    # 统一的交易对符号
    symbol = 'RARE/USDT'

    try:
        while True:
            # 创建任务来同时获取 Binance 和 Bitget 的数据
            binance_task = asyncio.create_task(fetch_data(binance, symbol))
            bitget_task = asyncio.create_task(fetch_data(bitget, symbol))

            # 等待所有任务完成
            binance_ticker, bitget_ticker = await asyncio.gather(binance_task, bitget_task)

            # 输出结果
            print(f"Binance:",binance_ticker["last"])
            print(f"Bitget:",bitget_ticker["last"])
            print(binance_ticker["last"] - bitget_ticker["last"])
            

            # 每隔一秒执行一次
            await asyncio.sleep(1)
    
    except asyncio.CancelledError:
        # 清理资源
        await binance.close()
        await bitget.close()

async def main():
    # 开始数据抓取循环
    fetch_task = asyncio.create_task(fetch_loop())

    try:
        # 等待 fetch_loop 完成（它会一直运行，直到手动停止）
        await fetch_task
    except KeyboardInterrupt:
        # 停止循环
        fetch_task.cancel()
        await fetch_task

# 运行异步主函数
asyncio.run(main())
